package com.tianci.appstore.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import com.alibaba.fastjson.JSONObject;

public class Tools {

    public static long getVersionFromString(String str) {
        String subStr = "";
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) >= 48 && str.charAt(i) <= 57) {
                subStr += str.charAt(i);
            }
        }
        if (subStr.equals("")) {
            return 0;
        } else {
            return (int) Long.parseLong(subStr);
        }
    }

    public static String gussName(String url) {
        int index = url.lastIndexOf("/");
        String subString = url.substring(index + 1);
        return subString;
    }

    public static float fixFloat(float f) {
        BigDecimal b = new BigDecimal(f);
        float f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
        return f1;
    }

    @SuppressWarnings("unchecked")
    public static <T> T toObject(byte[] bytes, Class<T> clazz) {
        try {
            Object obj = null;
            ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
            ObjectInputStream oi = new ObjectInputStream(bi);
            obj = oi.readObject();
            bi.close();
            oi.close();
            return (T) obj;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] toBytes(Object obj) {
        byte[] bytes = null;
        try {
            ByteArrayOutputStream bo = new ByteArrayOutputStream();
            ObjectOutputStream oo = new ObjectOutputStream(bo);
            oo.writeObject(obj);
            bytes = bo.toByteArray();
            bo.close();
            oo.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bytes;
    }

    public static String map2json(Map<String, String> map) {
        JSONObject t = (JSONObject) new JSONObject();
        Set<String> keys = map.keySet();
        for (String key : keys)
            t.put(key, map.get(key));
        return t.toString();
    }

    public static Map<String, String> json2map(String json) {
        Map<String, String> map = new HashMap<String, String>();
        JSONObject t = (JSONObject) JSONObject.parse(json);
        Set<String> keys = t.keySet();
        for (String key : keys)
            map.put(key, t.getString(key));
        return map;
    }
}
